import { createStore } from 'vuex'
import type { CartItem } from '../types'

interface UserState {
  id: number;
  username: string;
  role: string;
  avatar?: string;
  phone?: string;
  email?: string;
}

interface State {
  token: string;
  user: UserState | null;
  cart: CartItem[];
}

const getUserFromStorage = () => {
  try {
    const userStr = localStorage.getItem('user')
    // 检查 userStr 是否为 null、undefined 或 "undefined"
    if (!userStr || userStr === 'undefined') {
      return null
    }
    const user = JSON.parse(userStr)
    // 验证解析出的用户对象是否有效
    if (!user || typeof user !== 'object') {
      return null
    }
    return user
  } catch (e) {
    console.error('Failed to parse user from localStorage:', e)
    // 清除无效的用户数据
    localStorage.removeItem('user')
    return null
  }
}

export default createStore({
  state: {
    token: localStorage.getItem('token') || '',
    user: getUserFromStorage(),
    cart: []
  },
  mutations: {
    setToken(state, token: string) {
      state.token = token
      localStorage.setItem('token', token)
    },
    setUserInfo(state, user: UserState) {
      state.user = user
      if (user && user.id) {
        localStorage.setItem('user', JSON.stringify(user))
      }
    },
    clearToken(state) {
      state.token = ''
      state.user = null
      state.cart = [] // 清空购物车
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('role')
    },
    // 恢复购物车相关的 mutations
    addToCart(state, item: CartItem) {
      const existingItem = state.cart.find(i => i.dish.ID === item.dish.ID)
      if (existingItem) {
        existingItem.quantity += item.quantity
      } else {
        state.cart.push(item)
      }
    },
    updateCartItem(state, item: CartItem) {
      const index = state.cart.findIndex(i => i.dish.ID === item.dish.ID)
      if (index !== -1) {
        state.cart[index] = item
      }
    },
    removeFromCart(state, item: CartItem) {
      const index = state.cart.findIndex(i => i.dish.ID === item.dish.ID)
      if (index !== -1) {
        state.cart.splice(index, 1)
      }
    },
    clearCart(state) {
      state.cart = []
    }
  },
  getters: {
    // 添加一些有用的 getters
    isAuthenticated: state => !!state.token,
    isAdmin: state => state.user?.role === 'admin',
    cartTotal: state => state.cart.reduce((total, item) => total + item.quantity * item.dish.price, 0),
    cartItemCount: state => state.cart.reduce((count, item) => count + item.quantity, 0)
  }
}) 